package cc.stonemarket.caricature.util;

import android.app.Dialog;
import android.os.AsyncTask;
import android.util.Log;

public final class TaskUtil {

	private static final String TAG = "TaskUtil";

	private TaskUtil() { }

	// AsyncTasks are odd beasts, very helpful, but can also be confusing
	// you need to keep a reference to an instance, so you can cleanup in
	// onPause, etc (or leak windows)
	// but you can only "execute" once, so you have to create new instances for
	// your reference
	// if an old instance is still around (orientation change, fast clicks,
	// etc., problems ensue
	// this is an attempt to consolidate handling around AsyncTask

	public static void dismissDialog(final Dialog dialog) {
		if (dialog != null && dialog.isShowing()) {
			dialog.dismiss();
		}
	}

	public static void pauseTask(final AsyncTask<?, ?, ?> task) {
		if (task != null) {
			if (!task.isCancelled() && !task.getStatus().equals(AsyncTask.Status.FINISHED)) {
				Log.w(TAG, "AsyncTask not finished at onPause (status " + task.getStatus() + "), trying to cancel.");
				task.cancel(true);
			}
		}
	}

}
